import json
import socket
import telnetlib


class Dubbo(telnetlib.Telnet):
    prompt = 'dubbo>'
    coding = 'utf-8'

    def __init__(self, host=None, port=0,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        super().__init__(host, port)
        self.write(b"\n")

    def command(self, flag, str_=""):
        data = self.read_until(flag.encode())
        self.write(str_.encode() + b"\n")
        return data

    def invoke(self, service_name, method_name, arg):
        command_str = "invoke {0}.{1}({2})".format(
            service_name, method_name, arg)  # 这个地方的arg不能写成json.dumps(arg)，即不能转换成string型，提高复用性，在调2个或2个以上的接口的方法的参数时
        self.command(Dubbo.prompt, command_str)
        data = self.command(Dubbo.prompt, "")
        data = data.decode(Dubbo.coding, errors='ignore').split('\n')[0].strip()

        return data

    def dotest1(self, conn, data):  # 含有泛型的json，看源码
        result = conn.invoke("com.xxx.bluespar.star.service.BudgetService", "recBudgetDetail", data)
        # print("==========请求data参数为:==========" + str(data))
        return result


if __name__ == '__main__':
    # count = 10001
    # for num in range(20190919200001, 20190919200006, 2):
    #     count += 100
    conn = Dubbo('10.9.48.115', 28899)  # 这个是dubbo://的IP和端口

    # T_E006_BUDGET_DETAIL
    data1 = {
        "budgetId": "HKYF201908000003",
        "businessNo": "BN201908000003",
        "sendDate": "2019-08-24 10:42:20",
        "bill": "测试001",
        "secondBill": "测试001_second",
        "transName": "测试transName",
        "startCustomerId": "982",
        "startCustomerName": "苏州",
        "startCityId": "320500",
        "startCityName": "苏州",
        "startAirportName": "无锡",
        "endCustomerId": "522",
        "endCustomerName": "金华",
        "endCityId": "330700",
        "endCityName": "金华",
        "endAirportName": "广州",
        "flightType": 1,
        "flightNo": "GZ568888",
        "secFlightNo": "GZ568888_001",
        "pickLocationName": "广州",
        "goodsTypeName": "广州",
        "sendBillCount": 200,
        "sendGrossWeight": 8935.66,
        "sendCalWeight": 8955.55,
        "pickBillCount": 1122.66,
        "pickGrossWeight": 898.66,
        "pickCalWeight": 55.88,
        "computeWeight": 223.33,
        "financeReviewWeight": 88.66,
        "reviewWeight": 120.33,
        "computeModeName": "结算",
        "settleModeName": "结算",
        "computePrice": 55.2,
        "feeKindsName": "费用类型名",
        "feeValue": 500.2,
        "settleInCustId": "982",
        "settleInCustName": "苏州",
        "settleOutCustId": "522",
        "settleOutCustName": "金华",
        "remark": "备注一下"
    }

    result1 = conn.dotest1(conn, data1)  # 执行dotest_json_param测试用例（请求是json格式的）
    print(result1)